package com.shuwen.gcdj.controller.member;

import com.shuwen.gcdj.bean.AddResp;
import com.shuwen.gcdj.bean.VoidResp;
import com.shuwen.gcdj.bean.member.request.*;
import com.shuwen.gcdj.bean.member.response.LoginResp;
import com.shuwen.gcdj.bean.member.response.UserDetailResp;
import com.shuwen.gcdj.bean.member.response.UserListItemResp;
import com.shuwen.gcdj.bean.member.response.UserListWithoutAuthItemResp;
import com.shuwen.gcdj.common.annotation.JWTAuth;
import com.shuwen.gcdj.common.api.CommonPage;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.enums.ErrorCode;
import com.shuwen.gcdj.common.enums.LogModuleEnum;
import com.shuwen.gcdj.common.enums.LogTypeEnum;
import com.shuwen.gcdj.common.error.ErrorReport;
import com.shuwen.gcdj.common.sysLog.AddSysLogUtil;
import com.shuwen.gcdj.common.util.paging.PagingUtil;
import com.shuwen.gcdj.controller.AuthController;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.service.account.AccountRoleService;
import com.shuwen.gcdj.service.account.AccountService;
import com.shuwen.gcdj.service.role.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
/**
 * @oauth 潘思逸
 * @createDate 2023/03/15
 *
 * @info
 */

@Api(tags = "用户中心 - 用户管理")
@RestController
@RequestMapping("/account")
@Slf4j
public class AccountController extends AuthController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private AddSysLogUtil addSysLogUtil;


    @Autowired
    private RoleService roleService;

    @Autowired
    private AccountRoleService accountRoleService;

    @ApiOperation(value = "登录接口")
    @PostMapping(value = "/login")
    @ResponseBody
    public CommonResult<LoginResp> login(HttpServletRequest request, @Valid @RequestBody LoginReq req) {
        CommonResult<LoginResp> resp = accountService.login(req);
        Long code = resp.getCode();
        if (code.equals(ErrorCode.SUCCESS.getCode())){
            addSysLogUtil.addLoginLog(resp.getData(), LogTypeEnum.LOG_TYPE_LOGIN.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(), "登录了本系统");
        }
        return resp;
    }

    @ApiOperation(value = "刷新用户权限")
    @GetMapping(value = "/refresh")
    @ResponseBody
    @JWTAuth
    public CommonResult<LoginResp> refresh(HttpServletRequest request) {
        InitUserDto initUserDto = initUser(request);
        if (initUserDto == null || initUserDto.getUserId() == null) {
            log.info("error: AccountController.refresh() token has expired");
            return CommonResult.failed(ErrorCode.UNAUTHORIZED);
        }
        String jwtToken = getJwtToken(request);
        return accountService.refresh(initUserDto.getUserId(), jwtToken);
    }

    @ApiOperation(value = "退出登录")
    @GetMapping(value = "/logout")
    @ResponseBody
    @JWTAuth
    public CommonResult<VoidResp> logout(HttpServletRequest request) {
        return accountService.logout(initUser(request));
    }



    @ApiOperation(value = "用户基本信息列表(无需授权)")
    @PostMapping(value = "/getBaseInfoList")
    @ResponseBody
    @JWTAuth
    public CommonResult<CommonPage<UserListWithoutAuthItemResp>> getBaseInfoList(HttpServletRequest request, @Valid @RequestBody UserListAdminReq req) {
        InitUserDto initUserDto = initUser(request);
        if (StringUtils.isEmpty(initUserDto) || StringUtils.isEmpty(initUserDto.getUserId())) {
            CommonResult.failed(ErrorCode.UNAUTHORIZED);
        }
        PagingUtil.withDefault(req);
        return accountService.getBaseInfoList(req, initUserDto);
    }


    @ApiOperation(value = "用户列表分页")
    @PostMapping(value = "/getListPage")
    @ResponseBody
    @JWTAuth
    public CommonResult<CommonPage<UserListItemResp>> getUserListPage(HttpServletRequest request, @Valid @RequestBody UserListAdminReq req) {
        PagingUtil.withDefault(req);
        return accountService.getAdminListPage(req, initUser(request));
    }

    @ApiOperation(value = "用户列表")
    @PostMapping(value = "/getList")
    @ResponseBody
    @JWTAuth
    public CommonResult<List<UserListItemResp>> getUserList(HttpServletRequest request, @Valid @RequestBody UserListAdminReqNoPage req) {
        return accountService.getAdminList(req, initUser(request));
    }


    @ApiOperation(value = "用户详情")
    @GetMapping(value = "/detail/{userId}")
    @ResponseBody
    @JWTAuth
    public CommonResult<UserDetailResp> getDetail(HttpServletRequest request, @Valid @PathVariable String userId) {
        return accountService.getDetail(userId);
    }

    @ApiOperation(value = "用户批量删除")
    @PostMapping(value = "/delete/{userId}")
    @ResponseBody
    @JWTAuth
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> deleteUser(HttpServletRequest request, @Valid @PathVariable String userId) {
        InitUserDto initUserDto = initUser(request);
        return accountService.deleteUser(userId,initUserDto);
    }

    @ApiOperation(value = "用户修改")
    @PostMapping(value = "/update")
    @ResponseBody
    @JWTAuth
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> update(HttpServletRequest request, @Valid @RequestBody UserUpdataReq req) {
        InitUserDto initUserDto = initUser(request);
        CommonResult<String> commonResult = accountService.updateUser(req, initUserDto);
        Long code=commonResult.getCode();
        if (code.equals(ErrorCode.SUCCESS.getCode())){
            addSysLogUtil.addLog(initUserDto, LogTypeEnum.LOG_TYPE_UPDATE.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(),"修改了用户",req);
        }
        return commonResult;
    }

    @ApiOperation(value = "新增用户")
    @PostMapping(value = "/add")
    @ResponseBody
    @JWTAuth
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<AddResp> add(HttpServletRequest request, @Valid @RequestBody UserAddReq req) {
        InitUserDto initUserDto = initUser(request);
        CommonResult<AddResp> resp = accountService.add(req, initUserDto);
        Long code =resp.getCode();
        if (code.equals(ErrorCode.SUCCESS.getCode())) {
            addSysLogUtil.addLog(initUserDto, LogTypeEnum.LOG_TYPE_ADD.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(), "新增用户" + req.getLoginName(), req);
        }
        return resp;
    }

    @ApiOperation(value = "用户绑定多角色")
    @PostMapping(value = "/bindRoles")
    @ResponseBody
    @JWTAuth
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<VoidResp> bindRoles(HttpServletRequest request, @Valid @RequestBody UserBindRolesReq req) {
        InitUserDto initUserDto = initUser(request);
        CommonResult<VoidResp> resp = accountService.bindRoles(req, initUserDto);
        Long code = resp.getCode();
        if (code.equals(ErrorCode.SUCCESS.getCode())) {
            addSysLogUtil.addLog(initUserDto, LogTypeEnum.LOG_TYPE_UPDATE.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(), "绑定角色给" + req.getUserId(), req);
        }
        return resp;
    }

    @ApiOperation(value = "账户是否启用设置")
    @PostMapping(value = "/activeSetting")
    @ResponseBody
    @JWTAuth
    public CommonResult<VoidResp> activeSetting(HttpServletRequest request, @Valid @RequestBody UserActiveReq req) {
        InitUserDto initUserDto = initUser(request);
        CommonResult<VoidResp> voidRespCommonResult = accountService.activeSetting(req, initUserDto);
        Long code = voidRespCommonResult.getCode();
        if (code.equals( ErrorCode.SUCCESS.getCode())) {
            addSysLogUtil.addLog(initUserDto, LogTypeEnum.LOG_TYPE_UPDATE.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(), "绑定角色给" + req.getUserId(), req);
        }
        return voidRespCommonResult;
    }

    @ApiOperation(value = "重置密码(仅限超管)")
    @PostMapping(value = "/resetPwd")
    @ResponseBody
    @JWTAuth
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<VoidResp> resetPwd(HttpServletRequest request, @Valid @RequestBody UserResetPwdReq req) {
        InitUserDto initUserDto = initUser(request);
        CommonResult<VoidResp> voidRespCommonResult = accountService.resetPwd(req, initUserDto);
        Long code = voidRespCommonResult.getCode();
        if (code.equals( ErrorCode.SUCCESS.getCode())) {
            addSysLogUtil.addLog(initUserDto, LogTypeEnum.LOG_TYPE_UPDATE.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(), "重置密码" + initUserDto.getUserId(), req);
        }
        return voidRespCommonResult;
    }

    @ApiOperation(value = "重置密码")
    @PostMapping(value = "/updatePwd")
    @ResponseBody
    @JWTAuth
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<VoidResp> updatePwd(HttpServletRequest request, @Valid @RequestBody UserUpdatePwdReq req) {
        InitUserDto initUserDto = initUser(request);
        CommonResult<VoidResp> voidRespCommonResult = accountService.updatePwd(req, initUserDto);
        Long code = voidRespCommonResult.getCode();
        if (code.equals( ErrorCode.SUCCESS.getCode())) {
            addSysLogUtil.addLog(initUserDto, LogTypeEnum.LOG_TYPE_UPDATE.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(), "重置密码" + initUserDto.getUserId(), req);
        }
        return voidRespCommonResult;
    }

    @ApiOperation(value = "账户绑定部门")
    @PostMapping(value = "/bindDept")
    @ResponseBody
    @JWTAuth
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<VoidResp> bindDepartmentId(HttpServletRequest request, @Valid @RequestBody UserBindDeptReq req) {
        InitUserDto initUserDto = initUser(request);
        CommonResult<VoidResp> voidRespCommonResult = accountService.bindDept(req, initUserDto);
        Long code = voidRespCommonResult.getCode();
        if (code.equals( ErrorCode.SUCCESS.getCode())) {
            addSysLogUtil.addLog(initUserDto, LogTypeEnum.LOG_TYPE_UPDATE.getTypeNum(), LogModuleEnum.LOG_MODULE_USER.getModuleNum(), "绑定部门给" + initUserDto.getUserId(), req);
        }
        return voidRespCommonResult;
    }

    @ApiOperation(value = "Api权限验证")
    @PostMapping(value = "/auth/{apiCode}/{userId}")
    @ResponseBody
    public CommonResult<VoidResp> authApi(@Valid @PathVariable String apiCode, @Valid @PathVariable String userId) {
        ErrorCode code = accountService.apiAccess(userId, apiCode);
        if (ErrorReport.hasError(code)) {
            return CommonResult.failed(code);
        }
        return CommonResult.success(new VoidResp());
    }
}
